import cgi
import os
import urllib
import logging
import random

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from app.models import assist, deposit, payment, household

from reportlab.pdfgen import canvas
from reportlab.platypus.tables import *
from reportlab.platypus.tables import (_rowLen, _calc_pc, _hLine, _multiLine,
    _convert2int, _endswith, _isLineCommand, _setCellStyle)

from formula import Formula

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, BaseDocTemplate, Frame, PageTemplate, FrameBreak
from reportlab.lib.units import inch
from reportlab.platypus.flowables import PageBreak, Spacer
from reportlab.platypus.paragraph import Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors

from formula import CurrentPageColSum, PreviousPagesColSum, TotalPagesColSum, \
    RowNumber
from spreadsheettable import SpreadsheetTable

_DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'user': users.GetCurrentUser(),
      'login_url': users.CreateLoginURL(self.request.uri),
      'logout_url': users.CreateLogoutURL(self.request.uri),
      'application_name': 'CMS',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))




styleSheet = getSampleStyleSheet()
MARGIN_SIZE = .75 * inch
PAGE_SIZE = letter
TABLE_HEIGHT = 7.5 * inch
TOP_HEIGHT = PAGE_SIZE[1] - (TABLE_HEIGHT + 2 * MARGIN_SIZE)



def create_pdfdoc(pdfdoc, story):
    """
    Creates PDF doc from story.
    """
    doc = BaseDocTemplate(pdfdoc, pagesize = PAGE_SIZE,
                          leftMargin = MARGIN_SIZE, rightMargin = MARGIN_SIZE,
                          topMargin = MARGIN_SIZE, bottomMargin = MARGIN_SIZE)

    
    #normal frame as for SimpleFlowDocument
    frameT = Frame(MARGIN_SIZE, MARGIN_SIZE + TABLE_HEIGHT, doc.width, TOP_HEIGHT, id='top')
    
    #Two Columns
    frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, TABLE_HEIGHT, id='col1')
    frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6,
                   TABLE_HEIGHT, id='col2')

    main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE,
        PAGE_SIZE[0] - 2 * MARGIN_SIZE, PAGE_SIZE[1] - 2 * MARGIN_SIZE,
        leftPadding = 0, rightPadding = 0, bottomPadding = 0,
        topPadding = 0, id = 'main_frame')
    main_template = PageTemplate(id = 'main_template', frames = [frameT, frame1, frame2])
    doc.addPageTemplates([main_template])

    doc.build(story)


class PrintYearly(webapp.RequestHandler):

    def get(self, household_id):

        this_household = household.Household.get_by_id(int(household_id))

        story = []

        table_style = [  
          ('ALIGN', (0,0), (-1,-1), 'CENTER'),
          ('ALIGN', (1,1), (1,-1), 'RIGHT'),
          ('LEFTPADDING', (0,0), (-1,-1), 1),  
          ('RIGHTPADDING', (0,0), (-1,-1), 1),  
          ("BOTTOMPADDING",[0,0],[-1,-1],0),
          ("TOPPADDING",[0,0],[-1,-1],0),
          ('FONTSIZE', (0,0), (-1,-1), 8),  
          ('FONTNAME', (0,0), (-1,0), 'Times-Bold'),  
          ]  


        story.append(Paragraph("Verdigris Valley Christian Fellowship, PO Box 126, Altoona, KS  66710", styleSheet['Heading2']))
        story.append(Paragraph("2010 Giving Statement", styleSheet['Heading3']))

        story.append(Paragraph(cgi.escape("For: " + this_household.name + ", " + this_household.address), styleSheet['Heading4']))
        story.append(Paragraph("This is a record of your tithes, offerings, and missions giving \
to VVCF for 2010. No tangible benefit was received for the donations listed in this statement.", styleSheet['BodyText']))
        story.append(Spacer(0, .4 * inch))
        story.append(FrameBreak())
        data = [['Date', 'Amount','Type','Check','Category']]
        
        total = 0
        pays = payment.Payment.all().filter('household = ', db.Key.from_path('Household', int(household_id))).filter('year =', '2010').filter('fund IN ', ('Tithes / Offerings', 'Missions')).order('date')
        for pay in pays:
          total += pay.amount
          data.append([pay.date, "$%.2f" % pay.amount, pay.paytype, pay.checkno, pay.fund])

        table_style[-1] = ['FONTNAME', (0,-1), (-1,-1), 'Times-Bold']
        table_style[-1] = ['FONTSIZE', (0,-1), (-1,-1), 12]
            
        data.append(['Total:', "$%.2f" % total])
        # spreadsheet_table = SpreadsheetTable(data, repeatRows = 1, repeatRowsB = 3)
        spreadsheet_table = SpreadsheetTable(data)
        spreadsheet_table.setStyle(table_style)
        story.append(spreadsheet_table)

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()

        # A basic document for us to write to 'rl_hello_table.pdf'
        doc = SimpleDocTemplate(self.response.out, pagesize=letter, rightMargin = 60, leftMargin = 60,
                                topMargin = 60, bottomMargin = 18)

    # Write the document to response
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=my.pdf'
        create_pdfdoc(self.response.out, story) 

        # p = create_pdfdoc(self.response.out, story)


class HouseholdList(BaseRequestHandler):
  def get(self):
    households = household.Household.all().order('name')
    self.generate('householdList.html', {
        'households': households })

class MainPage(BaseRequestHandler):
  def get(self):
    self.generate('views.html')


application = webapp.WSGIApplication([('/report/household/(.*)', PrintYearly),
                                      ('/report/households', HouseholdList),
                                      ('/report/', MainPage)
                                     ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()  
